//
//  PageControl.swift
//
//
//  Created by 李加建 on 2022/11/17.
//

import UIKit

class PageControl: UIControl {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var numberOfPages: Int = 0 {
        didSet {
            createUIs()
        }
    }

    var currentPage: Int = 0 {
        didSet {
            updateUIs()
        }
    }

    var pageDotColor: UIColor?

    var currentPageDotColor: UIColor?

    var dotSize: CGSize = .init(width: 8, height: 8)

    var dotSpace: CGFloat = 8

    var dotCornerRadius: CGFloat = 4

    private lazy var dotArray: [UIView] = []

    private var contentWidth: CGFloat = 0

    func setup() {}

    func createUIs() {
        for dotView in dotArray {
            dotView.removeFromSuperview()
        }
        dotArray.removeAll()

        if numberOfPages > 0 {
            let s = CGFloat(numberOfPages)
            let s1 = dotSize.width * s
            let s2 = (s - 1) * dotSpace
            contentWidth = s1 + s2
        }

        for index in 0 ..< numberOfPages {
            let dot = UIView(frame: CGRect(origin: .zero, size: dotSize))
            addSubview(dot)
            dot.tag = index
            dot.layer.cornerRadius = dotCornerRadius
            dotArray.append(dot)
            if currentPage == index {
                dot.backgroundColor = currentPageDotColor
            } else {
                dot.backgroundColor = pageDotColor
            }
        }
    }

    func updateUIs() {
        let offsetX = (frame.width - contentWidth) / 2
        for index in 0 ..< numberOfPages {
            let dot = dotArray[index]
            let pointX = (dotSize.width + dotSpace) * CGFloat(index) + offsetX
            dot.frame = CGRect(origin: CGPoint(x: pointX, y: 0), size: dotSize)

            if currentPage == index {
                dot.backgroundColor = currentPageDotColor
            } else {
                dot.backgroundColor = pageDotColor
            }
        }
    }
}
